package com.keter.dtx.service;

import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @author jimin.jm@alibaba-inc.com
 * @date 2019/06/14
 */
@Service
public class BusinessService {

    @Autowired  RestTemplate restTemplate;

    String DTX_SERVICE = "http://dtx-service";
    /**
     * 减库存，下订单
     *
     * @param userId
     * @param commodityCode
     * @param orderCount
     */
    @GlobalTransactional
    public boolean purchase(String userId, String commodityCode, int orderCount) {
        String result1 = restTemplate.getForObject(DTX_SERVICE+"/deduct/{commodityCode}/{orderCount}",String.class,commodityCode,orderCount);
        String result2 = restTemplate.getForObject(DTX_SERVICE+"/create/{userId}/{commodityCode}/{orderCount}",String.class,userId,commodityCode,orderCount);
        if (!validData()) {
            throw new RuntimeException("账户或库存不足,执行回滚");
        }
        return Boolean.valueOf(result1) && Boolean.valueOf(result2);
    }

    public boolean validData() {
       return restTemplate.getForObject(DTX_SERVICE+"/validate",Boolean.class);
    }
}
